package com.apache.uct.service.impl;

import java.util.List;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.tools.StrUtil;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.RoleOrg;
import com.apache.uct.manager.RoleManager;
import com.apache.uct.util.UctStringUtil;

public class RoleManagerImpl implements RoleManager {

	protected IDao roleDao;
	private IDao roleOrgDao;
	private IDao orgDao;
	protected final String entityName = "com.apache.uct.common.entity.Role";

	public void setRoleDao(IDao roleDao) {
		this.roleDao = roleDao;
	}

	public void setRoleOrgDao(IDao roleOrgDao) {
		this.roleOrgDao = roleOrgDao;
	}

	public void setOrgDao(IDao orgDao) {
		this.orgDao = orgDao;
	}

	public String saveInfo(ParamsVo<Role> vo) throws BusinessException {
		Role role = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="role_"+infoId;
		role.setRoleId(infoId);
		MethodParam param = new MethodParam("Role", cacheKey, "", entityName);
		String orgId = String.valueOf(vo.getParams("orgId"));
		param.setVaule(role);
		if (roleDao.insert(param)) {
			if (Validator.isNotNull(orgId)) {
				saveRoleOrg(role, orgId, String.valueOf(vo.getParams("synchSub")));
			}
			return infoId;
		}
		return "";
	}

	//保存角色机构关系
	private void saveRoleOrg(Role role, String orgId, String synchSub) {
		if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
			RoleOrg ro = new RoleOrg();
			ro.setRoleOrgId(Validator.generate());
			ro.setOrgId(orgId);
			ro.setRoleId(role.getRoleId());
			MethodParam param = new MethodParam("RoleOrg", "", "", entityName);
			param.setVaule(ro);
			roleDao.insert(param);
			if ("1".equals(synchSub)) {//是否同步到子机构
				param = new MethodParam("ById", "", "", Org.class.getName());
				param.setInfoId(orgId);
				Org org = (Org) orgDao.selectById(param);
				param.setKey("ByOrgEname");
				param.setParams("orgId", orgId);
				param.setParams("fullEname", "'%" + org.getOrgEname() + "%'");
				List list = orgDao.select(param);
				if (!Validator.isEmpty(list)) {
					for (int i = 0; i < list.size(); i++) {
						String roleId = Validator.generate();
						Role roleV = (Role) StrUtil.clone(role);
						roleV.setRoleId(roleId);
						roleV.setRoleEname(roleV.getRoleEname() + "-" + i);
						param = new MethodParam("Role", "", "", entityName);
						param.setVaule(roleV);
						roleDao.insert(param);
						Org o = (Org) list.get(i);
						RoleOrg rog = new RoleOrg();
						rog.setRoleOrgId(Validator.generate());
						rog.setOrgId(o.getOrgId());
						rog.setRoleId(roleId);
						param = new MethodParam("RoleOrg", "", "", entityName);
						param.setVaule(rog);
						roleDao.insert(param);
					}
				}
			}
		}
	}

	public boolean editInfo(ParamsVo<Role> vo) throws BusinessException {
		Role role = vo.getObj();
		if (Validator.isNotNull(role.getRoleId())) {
			String cacheKey = "";
			//String cacheKey="role_"+role.getRoleId();
			MethodParam param = new MethodParam("Role", cacheKey, "", entityName);
			param.setVaule(role);
			return roleDao.edit(param);
		}
		return false;
	}

	public boolean deleteInfo(ParamsVo<Role> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		String key = vo.getKey();
		if (Validator.isNotNull(key)) {//删除角色机构关系
			if ("role".equals(key)) {
				deleteRoleOrg("", infoId);
			} else {
				deleteRoleOrg(infoId, "");
			}
			return true;
		}
		String cacheKey = "";
		//String cacheKey="role_"+infoId;
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		Role info = (Role) roleDao.selectById(param);
		if (Validator.isEmpty(info)) {
			return false;
		}
		param.setVaule(info);//此处需要先将状态值赋值为删除状态
		if ("false".equals(mark)) {//逻辑删除
			param.setKey("Role");
			return roleDao.edit(param);
		} else {
			param.setParams("roleId", infoId);
			param.setDelete(true);
			return roleDao.delete(param);
		}
	}

	//删除角色机构关系
	private void deleteRoleOrg(String orgId, String roleId) {
		MethodParam param = new MethodParam("ByRoleOrgobjId", "", "", Role.class.getName());
		String hql = roleOrgDao.getSql(3);
		if (Validator.isNotNull(roleId)) {
			hql += " roleId=:roleId";
			param.setParams("roleId", roleId);
		} else {
			hql += " orgId=:orgId";
			param.setParams("orgId", orgId);
		}
		param.setSqlStr(hql);
		param.setDelete(true);
		roleOrgDao.delete(param);
	}

	public Object getInfoById(ParamsVo<Role> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="role_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return roleDao.selectById(param);
	}

	public Object execute(ParamsVo<Role> vo) {
		String key = vo.getKey();
		if ("checkRoleEname".equals(key)) {
			Role role = vo.getObj();
			return checkRoleEname(role.getRoleEname());
		} else if ("ByUserEname".equals(key)) {
			String userEname = String.valueOf(vo.getParams("userEname"));
			return getRolesByUserEname(userEname);
		}
		return null;
	}

	private List getRolesByUserEname(String userEname) {
		if (Validator.isNull(userEname))
			return null;
		MethodParam param = new MethodParam("ByUserEname", "", "", entityName);
		param.setParams("userEname", userEname);
		param.setSqlStr(roleDao.getSql(2) + " and roleId in(select roleId from RoleGive where userEname=:userEname)");
		return roleDao.select(param);
	}

	private boolean checkRoleEname(String roleEname) {
		MethodParam param = new MethodParam("ByRoleEname", "", roleDao.getSql(1) + " and roleEname=:roleEname",
				entityName);
		param.setParams("roleEname", roleEname);
		long count = roleDao.count(param);
		if (count > 0)
			return false;
		return true;
	}

	public Page getPageInfo(ParamsVo<Role> vo) {
		String orderBy = vo.getKey();
		if (Validator.isNull(orderBy))
			orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		param.setOrderby(orderBy + " desc");
		Page page = roleDao.pageSelect(param);
		return page;
	}

	public List<Role> getList(ParamsVo<Role> vo) {
		String orderBy = vo.getKey();
		if (Validator.isNull(orderBy))
			orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		param.setOrderby(orderBy + " desc");
		return roleDao.select(param);
	}

	public long countInfo(ParamsVo<Role> vo) {
		MethodParam param = setMethodParams(vo, 1, "");
		return roleDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<Role> vo, int type, String orderBy) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer();
		String orgId = String.valueOf(vo.getParams("orgId"));
		if (Validator.isNull("")) {
			sb = new StringBuffer(roleDao.getSql(type));
		}
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		Role role = vo.getObj();
		if (Validator.isNotNull(role.getSysEname())) {
			sb.append(" and sysEname =:sysEname");
			param.setParams("sysEname", role.getSysEname());
		}
		if (Validator.isNotNull(role.getRoleEname())) {
			sb.append(" and roleEname =:roleEname");
			param.setParams("roleEname", role.getRoleEname());
		}
		if (Validator.isNotNull(role.getRoleCname())) {
			sb.append(" and roleCname =:roleCname");
			param.setParams("roleCname", role.getRoleCname());
		}
		if (Validator.isNotNull(role.getRoleRemark())) {
			sb.append(" and roleRemark =:roleRemark");
			param.setParams("roleRemark", role.getRoleRemark());
		}
		if (Validator.isNotNull(role.getCreateUser())) {
			sb.append(" and createUser =:createUser");
			param.setParams("createUser", role.getCreateUser());
		}
		if (Validator.isNotNull(role.getUpdateUser())) {
			sb.append(" and updateUser =:updateUser");
			param.setParams("updateUser", role.getUpdateUser());
		}
		if (Validator.isNotNull(orgId)) {//开启分级授权
			if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
				if (!"1".equals(String.valueOf(vo.getParams("sysUser")))) {
					sb = new StringBuffer();
					sb.append(roleDao.getSql(3));
					sb.append(" and orgId = :orgId");
					param.setParams("orgId", orgId);
					param.setKey("ByRoleOrgId");
				}
			}
		} else {
			if (Validator.isNotNull(role.getDelStatus())) {//存机构ID
				sb.append(" and delStatus =:delStatus");
				param.setParams("delStatus", role.getDelStatus());
			}
		}
		if (Validator.isNotNull(orderBy)) {
			sb.append(" order by " + UctStringUtil.toCamelNamed(orderBy) + " desc");
		}
		param.setSqlStr(sb.toString());
		return param;
	}
}
